<template>
    <div class="container">
        <div class="address">
            <!-- 地址渲染 -->
            <van-address-list :list="addressData" default-tag-text="默认" :switchable="false" class="address_list" />
            <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 0' }" dashed />
        </div>
        <div class="goods_list">
            <!-- 购物车商品渲染 -->
            <van-card v-for="item in goodsList" :num="item.count" :price="(item.goods_info.price / 100).toFixed(2)"
                :desc="item.goods_info.detail_info" :title="item.goods_info.name" :thumb="item.goods_info.pic_url" />
        </div>
        <van-submit-bar :price="countPrice" button-text="生成订单" @submit="show = true">
            <template #tip>
                <van-field v-model="remark" rows="2" autosize label="备注" type="textarea" maxlength="50" placeholder="备注"
                    show-word-limit />
            </template>
        </van-submit-bar>
        <van-action-sheet v-model:show="show" :actions="actions" cancel-text="取消" close-on-click-action
            @cancel="onCancel" @select="onSelect" />
    </div>
</template>

<script setup>
import { onMounted, ref, watchEffect, computed } from "vue";
import { useRoute } from "vue-router";
import { useRouter } from "vue-router";
import { getAddressList } from "@/api/address";
import { orderAdd } from "@/api/order";
import { storeToRefs } from "pinia";
import { cartDelete } from "@/api/cart";
import { showSuccessToast } from "vant";
import useCartInfo from "@/stores/useCartInfo";
import { getGoodsDetail } from "@/api/goods";

let route = useRoute();
let router = useRouter();

let cartStore = useCartInfo();
let { list } = storeToRefs(cartStore)

//动作面板 选项
const actions = [
    { name: '微信', pay_type: 1 },
    { name: '支付宝', pay_type: 2 },
    { name: '云闪付', pay_type: 3 },
]


// console.log(cartStore.list);

// 选中的地址
let addressData = ref([]);

// 选中的购物车数据
let goodsList = ref([]);

//控制 动作面板 显示影藏 
let show = ref(false)

// 获取地址数据
onMounted(async () => {
    // 调接口获取所有地址
    let arr = (await getAddressList({ limit: 100, page: 1 })).data.list;
    //   console.log(arr);
    // 过滤出 选中的地址
    let adressArr = arr.filter((item) => item.id == route.query.addressId);
    // 接口数据处理成组件 需要的数据
    addressData.value = adressArr.map((item) => {
        return {
            id: item.id,
            name: item.name,
            tel: item.phone,
            address: item.province + item.city + item.town + item.detail,
            isDefault: item.is_default === 1,
        };
    });
    //表示从商品页面下单
    if (route.query.goodsId) {
        let goodsInfo = (await getGoodsDetail({ id: route.query.goodsId })).data;
        let goodsItem = {
            count: 1,
            goods_info: goodsInfo,
            goods_id: route.query.goodsId
        }
        goodsList.value = [goodsItem]
    }

});

watchEffect(() => {
    //   cartStore.list  所有的 购物车数据
    //   console.log(route.query.checkedGoods.split(','));
    if (route.query.checkedGoods) {
        let goodsIds = route.query.checkedGoods.split(",");
        //[1,6,7,12].includes(666)   数组方法  判断 666  是否在前面的数组内

        // 过滤出选中的数据    cartStore.list仓库所有购物车数据  goodsIds是选中数据的id集合
        goodsList.value = cartStore.list.filter((item) =>
            goodsIds.includes(item.id.toString())
        );
    }

})

// 备注
let remark = ref('')

// 计算 选中的所有商品 总价
let countPrice = computed(() => {
    let countPrice = 0;
    goodsList.value.forEach((item) => {
        countPrice = countPrice + item.count * item.goods_info.price;
    });
    return countPrice;
});



// 点击了取消
let onCancel = async () => {
    const data = {
        remark: remark.value, //备注
        status: "1", //状态
        price: countPrice.value, //总价格
        order_goods_infos: goodsList.value.map((item) => {
            return {
                goods_id: item.goods_id,
                count: item.count,
            };
        }), // 商品列表
        addressId: addressData.value[0].id, //地址
    };
    // 调用接口 传递数据  生成订单
    await orderAdd(data);

    // 判断是购物车下单 还是直接下单
    if (route.query.checkedGoods) {
        // 从购物车内 删除 刚才已下单的商品
        cartDelete({ ids: goodsList.value.map((item) => item.id) });
        // 调用action  更新 购物车仓库数据
        cartStore.getCartInfo();
    }

    // 返回首页
    router.replace("/home");
};


// 选择了支付方式
let onSelect = async (action, index) => {
    // 创建接口需要的参数
    const data = {
        pay_type: action.pay_type, // 支付方式
        remark: remark.value, //备注
        status: "2", //状态
        price: countPrice.value, //总价格
        order_goods_infos: goodsList.value.map((item) => {
            return {
                goods_id: item.goods_id,
                count: item.count,
            };
        }), // 商品列表
        addressId: addressData.value[0].id, //地址
    };
    // 调用接口 传递数据  生成订单
    await orderAdd(data);
    showSuccessToast("生成订单成功");

    // 判断是购物车下单 还是直接下单
    if (route.query.checkedGoods) {
        // 从购物车内 删除 刚才已下单的商品
        cartDelete({ ids: goodsList.value.map((item) => item.id) });
        // 调用action  更新 购物车仓库数据
        cartStore.getCartInfo();
    }

    // 返回首页
    router.replace("/home");
};
// 获取所有购物车 数据  再通过id  过滤出当时 选中的购物车数据
//
</script>

<style lang="scss" scoped>
.container {
    --van-submit-bar-z-index: 100;
    --van-address-list-add-button-z-index: 1;
    --van-submit-bar-tip-background: #f0f0f0;

    .address {
        padding-top: 20px;
        background-color: #fff;

        .address_list {
            --van-address-list-padding: 0;

            //   :deep  样式穿透   将组件库内部的元素 样式  更改
            :deep(.van-badge__wrapper) {
                display: none;
            }
        }
    }

    .submit_box {
        background-color: #fff;
        bottom: 0;
        left: 0;
        right: 0;
        position: fixed;
        padding: 10px;
    }
}
</style>